package com.github.tvbox.osc.ui.fragment;

import android.os.Bundle;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.TextView;

import androidx.lifecycle.ViewModelProvider;
import io.github.source.media.bean.MediaBean;
import io.github.source.media.bean.MediaCategory;
import io.github.source.media.bean.MediaQuery;
import io.github.source.media.bean.MediaResult;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.github.tvbox.osc.R;
import com.github.tvbox.osc.base.BaseLazyFragment;
import com.github.tvbox.osc.ui.activity.DetailActivity;
import com.github.tvbox.osc.ui.activity.SearchActivity;
import com.github.tvbox.osc.ui.adapter.GridAdapter;
import com.github.tvbox.osc.ui.dialog.GridFilterDialog;
import com.github.tvbox.osc.ui.tv.widget.LoadMoreView;
import com.github.tvbox.osc.util.FastClickCheckUtil;
import com.github.tvbox.osc.viewmodel.SourceViewModel;
import com.owen.tvrecyclerview.widget.TvRecyclerView;
import com.owen.tvrecyclerview.widget.V7GridLayoutManager;

import java.util.List;

/**
 * @author pj567
 * @date :2020/12/21
 * @description:
 */
public class GridFragment extends BaseLazyFragment {
    private MediaCategory sortData = null;
    private TvRecyclerView mGridView;
    private SourceViewModel sourceViewModel;
    private GridFilterDialog gridFilterDialog;
    private GridAdapter gridAdapter;
    private int page = 1;
    private int maxPage = 1;
    private boolean isLoad = false;
    private boolean isTop = true;


    public static GridFragment newInstance(MediaCategory data) {
        return new GridFragment().setArguments(data);
    }

    public GridFragment setArguments(MediaCategory sortData) {
        this.sortData = sortData;
        return this;
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.fragment_grid;
    }

    @Override
    protected void onFragmentResume() {
        super.onFragmentResume();
    }

    @Override
    protected void init() {
        initView();
        initViewModel();
        initMediaData();
    }

    protected void initView() {
        mGridView = findViewById(R.id.mGridView);

        mGridView.setHasFixedSize(true);
        gridAdapter = new GridAdapter();
        mGridView.setAdapter(gridAdapter);
        mGridView.setLayoutManager(new V7GridLayoutManager(this.mContext, isBaseOnWidth() ? 5 : 6));
        gridAdapter.setOnLoadMoreListener(createLoadMoreListener(), mGridView);
        mGridView.setOnItemListener(createItemListener());
        mGridView.setOnInBorderKeyEventListener(createInBorderKeyEventListener());
        gridAdapter.setOnItemClickListener(createItemClickListener());
        gridAdapter.setLoadMoreView(new LoadMoreView());
        setLoadSir(mGridView);

    }

    private BaseQuickAdapter.RequestLoadMoreListener createLoadMoreListener() {
        return () -> {
            // 加载更多(控制不能加载更多了）
            gridAdapter.setEnableLoadMore(true);
            MediaQuery query = obtainQuery();
            sourceViewModel.fetchMediaList(query);
        };
    }

    private TvRecyclerView.OnItemListener createItemListener() {
        return new TvRecyclerView.OnItemListener() {
            @Override
            public void onItemPreSelected(TvRecyclerView parent, View itemView, int position) {
                itemView.animate().scaleX(1.0f).scaleY(1.0f).setDuration(300).setInterpolator(new BounceInterpolator()).start();
            }

            @Override
            public void onItemSelected(TvRecyclerView parent, View itemView, int position) {
                itemView.animate().scaleX(1.05f).scaleY(1.05f).setDuration(300).setInterpolator(new BounceInterpolator()).start();
            }

            @Override
            public void onItemClick(TvRecyclerView parent, View itemView, int position) {

            }
        };
    }

    private TvRecyclerView.OnInBorderKeyEventListener createInBorderKeyEventListener() {
        return (direction, focused) -> {
            if (direction == View.FOCUS_UP) {
            }
            return false;
        };
    }


    private BaseQuickAdapter.OnItemClickListener createItemClickListener() {
        return (adapter, view, position) -> {
            FastClickCheckUtil.check(view);
            MediaBean video = gridAdapter.getData().get(position);
            if (video != null) {
                Bundle bundle = new Bundle();
                bundle.putString("id", video.getVodId());
                bundle.putString("sourceKey", video.getSiteKey());
                bundle.putString("title", video.getVodName());
                if (video.getVodId() == null || video.getVodId().isEmpty() || video.getVodId().startsWith("msearch:")) {
                    jumpActivity(SearchActivity.class, bundle);
                } else {
                    jumpActivity(DetailActivity.class, bundle);
                }
            }
        };
    }

    private void initViewModel() {
        sourceViewModel = new ViewModelProvider(this).get(SourceViewModel.class);
        sourceViewModel.MediaBeanResult.observe(this, result -> {
            setMediaResultData(result);
            if (page > maxPage) {
                gridAdapter.loadMoreEnd();
            } else {
                gridAdapter.loadMoreComplete();
            }
        });

    }

    private void setMediaResultData(MediaResult<List<MediaBean>> result) {
        if (result != null && result.getData() != null && result.getData().size() > 0) {
            boolean showInit = gridAdapter.getData() == null || gridAdapter.getData().isEmpty();
            showSuccess();
            if (showInit) {//第一页（次）刷新
                isLoad = true;
                gridAdapter.setNewData(result.getData());
            } else {
                gridAdapter.addData(result.getData());
            }
            page++;
            maxPage = 999;
        } else {
            boolean showEmpty = gridAdapter.getData() == null || gridAdapter.getData().isEmpty();
            if (showEmpty) {
                showEmpty();
            } else {
                gridAdapter.setEnableLoadMore(false);
            }
        }
    }

    public boolean isLoad() {
        return isLoad;
    }

    protected void initMediaData() {
        gridAdapter.getData().clear();
        showLoading();
        isLoad = false;
        MediaQuery query = obtainQuery();
        sourceViewModel.fetchMediaList(query);
    }

    MediaQuery query = null;

    public MediaQuery obtainQuery() {
        query = MediaQuery.obtain();
        if (sortData != null) {
            query.setId(sortData.id);
        }
        query.page(page);
        return query;

    }

    public boolean isTop() {
        return isTop;
    }

    public void scrollTop() {
        isTop = true;
        mGridView.scrollToPosition(0);
    }

    public void showFilter() {
        if (!sortData.getFilters().isEmpty() && gridFilterDialog == null) {
            gridFilterDialog = new GridFilterDialog(mContext);
            gridFilterDialog.setData(sortData);
            gridFilterDialog.setOnDismiss(new GridFilterDialog.Callback() {
                @Override
                public void change() {
                    page = 1;
                    initData();
                }
            });
        }
        if (gridFilterDialog != null)
            gridFilterDialog.show();
    }

    /**
     * 开关过滤条件
     *
     * @param open
     */
    public void toggleFilter(boolean open) {
        if (open) showFilter();
        else hideFilter();
        mOpen = open;
    }

    boolean mOpen = false;

    public void hideFilter() {

    }

    public boolean canBack() {
        return true;
    }

    public void goBack() {
    }
}